package ch.abcm.remsmobile.REMSMobile.orm;

import java.sql.SQLException;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import ch.abcm.remsmobile.REMSMobile.R;
import ch.abcm.remsmobile.REMSMobile.orm.model.SystemState;
import ch.abcm.remsmobile.REMSMobile.orm.model.Treshhold;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

public class DatabaseOpenHelper extends OrmLiteSqliteOpenHelper {

	private static final String TAG = "DatabaseOpenHelper";

	private static final String DATABASE_NAME = "rems.db";
	private static final int DATABASE_VERSION = 2;

	private Dao<Treshhold, Integer> treshholdDao = null;
	private RuntimeExceptionDao<Treshhold, Integer> treshholdruntimeDao = null;
	private RuntimeExceptionDao<SystemState, Integer> systemStateRTEDao = null;

	public DatabaseOpenHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION, R.raw.ormlite_config);
	}

	@Override
	public void onCreate(SQLiteDatabase arg0, ConnectionSource arg1) {
		try {
			TableUtils.createTable(arg1, Treshhold.class);
			TableUtils.createTable(arg1, SystemState.class);
		} catch (SQLException e) {
			Log.e(TAG, e.getMessage(), e);
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase arg0, ConnectionSource arg1, int arg2, int arg3) {
		try {
			TableUtils.dropTable(arg1, Treshhold.class, true);
			TableUtils.dropTable(arg1, SystemState.class, true);
			onCreate(arg0);
		} catch (SQLException e) {
			Log.e(TAG, e.getMessage(), e);
		}
	}
	
	public Dao<Treshhold, Integer> getTresholdDao() throws SQLException {
		if (treshholdDao == null) {
			treshholdDao = getDao(Treshhold.class);
		}
		return treshholdDao;
	}
	
	public RuntimeExceptionDao<Treshhold, Integer> getTreshholdRuntimeExDao(){
		if (treshholdruntimeDao == null) {
			treshholdruntimeDao = getRuntimeExceptionDao(Treshhold.class);
		}
		return treshholdruntimeDao;
	}
	
	public RuntimeExceptionDao<SystemState, Integer> getSystemStateRTEDao() {
		if (systemStateRTEDao == null) {
			systemStateRTEDao = getRuntimeExceptionDao(SystemState.class);
		}
		return systemStateRTEDao;
	}
}
